回來囉,上次完成會員註冊、登入登出
這篇要讓你可以開始PO些文章囉~
讓我們很快複習一下開發流程 ...
這邊建立一個create_photo.html
,可以借用signup.html
改以下這段
<div class="container">
<h1>Share Photos</h1>
<form method="POST" action="/photo/create/post">
<label>Photo's title</label>
<input class="form-control" type="text" name="title">
<label>Photo's path</label>
<input class="form-control" type="text" name="path">
<label>Tell a story</label>
<input class="form-control" type="text" name="story"><br>
{% csrf_token %}
<button class="btn btn-primary btn-block">Submit</button>
</form>
</div>
from photos.views import get_photos_api, get_create_photo
url(r'^photo/create',get_create_photo)
這邊就是簡單的render出來
def get_create_photo(request):
return render(request,'create_photo.html')
以上都完成後,記得確認navbar的POST button 連結是否是到create_photo.html
先看看...
很好 ! 非常迅速的成功了 ~
這邊就是把讓剛剛的Form變得有意義,確實新建到資料庫!
from photos.views import get_photos_api, get_create_photo ,post_create_photo
url(r'^photo/create/post',post_create_photo),
我們import一個django的package forms
from django import forms
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ['title','path','story']
因為create是用POST,request後建立我們的object,再去檢查是否valid,確認就save起來redirect回index,失敗的話就在原地
def post_create_photo(request):
if request.method=='POST':
form = PhotoForm(request.POST)
if form.is_valid():
new_photo = form.save()
print(new_photo)
return redirect('/index')
else:
return redirect('/photo/create')
...
...
這樣就成功囉 !!